Shell Sort Algorithm
Shell Sort is an optimization of the insertion sort algorithm that improves its performance by reducing the number of comparisons and element shifts. It is named after its inventor, Donald Shell, who first published the algorithm in 1959. Unlike insertion sort, which compares and moves adjacent elements, Shell Sort compares elements that are a certain "gap" apart, gradually reducing the gap size until it reaches 1, at which point the final pass of the algorithm is equivalent to a regular insertion sort. This gap-based approach allows the algorithm to partially sort the array in earlier passes, reducing the overall number of comparisons and movements required.
The gap sequence is a crucial aspect of Shell Sort, as it directly impacts the algorithm's efficiency. Different gap sequences may yield different performance characteristics, and several variations have been proposed over the years, such as the original Shell's gap sequence (N/2, N/4, ..., 1), Knuth's gap sequence (1, 4, 13, ...), or the more recent Ciura's gap sequence. The choice of gap sequence will typically determine the time complexity of the algorithm, which can range from O(n^1.5) to O(n^2) in the worst case, depending on the chosen sequence. Despite its relatively high worst-case time complexity, Shell Sort is known for its simplicity, low overhead, and good performance on small to medium-sized arrays, making it a suitable choice for specific use cases.
#include <iostream>
using namespace std;
int main()
{
int size = 10;
int array[size];
// Input
cout << "\nHow many numbers do want to enter in unsorted array : ";
cin >> size;
cout << "\nEnter the numbers for unsorted array : ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
// Sorting
for (int i = size / 2; i > 0; i = i / 2)
{
for (int j = i; j < size; j++)
{
for (int k = j - i; k >= 0; k = k - i)
{
if (array[k] < array[k + i])
{
break;
}
else
{
int temp = array[k + i];
array[k + i] = array[k];
array[k] = temp;
}
}
}
}
// Output
cout << "\nSorted array : ";
for (int i = 0; i < size; ++i)
{
cout << array[i] << "\t";
}
return 0;
}